use std::sync::Mutex;
use std::time::Duration;
use tokio::time::sleep;
use crate::{EXECUTOR, THREAD_LOCAL_VAR};

// 定义一个全局的互斥锁包裹的变量
static _GLOBAL_VAR: Mutex<usize> = Mutex::new(0);

/// 获取线程名称
pub fn _get_thread_name(name: &str, max_task: usize) -> String {
    let mut thread_name = String::from("");
    THREAD_LOCAL_VAR.with(|local| {
        let thread_local_var = local.borrow();
        thread_name = String::from(thread_local_var.get_thread_name());
    });

    if thread_name.is_empty() {
        let mut num = _GLOBAL_VAR.lock().unwrap();
        if *num < max_task {
            *num = *num + 1;
        } else if *num >= max_task {
            *num = 1;
        }
        thread_name = String::from(format!("{}-{}", name, *num));

        THREAD_LOCAL_VAR.with(|local| {
            let mut thread_local_var = local.borrow_mut();
            thread_local_var.set_thread_name(thread_name.clone());
        });
    }

    thread_name
}

/// 等待线程池任务全部完成
/// TODO 任务数1分钟内一直相同，则强制结束
pub async fn wait_task_completed() {
    loop {
        let num_alive_tasks = EXECUTOR.metrics().num_alive_tasks();
        if num_alive_tasks == 0 {
            break;
        }

        log::debug!("请稍后，线程池中还有{}个任务待执行...", num_alive_tasks);
        sleep(Duration::from_secs(1)).await;
    }
}